package com.vitae.controller.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashSet;

/**
 * Created by Administrator on 2018/1/10.
 */
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent event) {

        //写在这里没有用 还是写在登陆请求的地方好些
        HttpSession session = event.getSession();
        if(session.getAttribute("user1")!= null){
            ServletContext application = session.getServletContext();
            // 在application范围由一个HashSet集保存所有的session
            HashSet sessions = (HashSet) application.getAttribute("sessions");
            if(sessions == null){
                sessions = new HashSet();
                application.setAttribute("sessions",sessions);
            }
            // 新创建的session均添加到HashSet集中
            sessions.add(session);
            // 可以在别处从application范围中取出sessions集合

            // 然后使用sessions.size()获取当前活动的session数，即为“在线人数”
        }

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext spplication = session.getServletContext();
        HashSet sessions = (HashSet) spplication.getAttribute("sessions");
        sessions.remove(session);
    }
}
